package com.cloud.common.log.utils;

import cn.hutool.core.util.URLUtil;
import com.cloud.api.upms.model.SysLog;
import com.cloud.common.core.constant.CommonConstants;
import com.cloud.common.core.util.JsonUtil;
import com.cloud.common.core.util.SpringContextUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.SneakyThrows;
import lombok.experimental.UtilityClass;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpHeaders;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.net.InetAddress;
import java.util.Date;
import java.util.Objects;

/**
 * Author:  xuanning
 * Date:    2022/10/26 19:46
 */
@UtilityClass
public class SysLogUtil {



    @SneakyThrows
    public SysLog getSysLog(){
        HttpServletRequest request = ((ServletRequestAttributes) Objects
                .requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();

        Environment env=SpringContextUtil.getBean(Environment.class);
        String port=env.getProperty(CommonConstants.port);
        String serviceName=env.getProperty(CommonConstants.serviceName);

        SysLog sysLog = new SysLog();
        sysLog.setStatus(1);
        sysLog.setServiceId(serviceName);
        sysLog.setIpAddr(InetAddress.getLocalHost().getHostAddress()+":"+port);
        sysLog.setRequestUri(URLUtil.getPath(request.getRequestURI()));
        sysLog.setMethod(request.getMethod());
        sysLog.setUserAgent(request.getHeader(HttpHeaders.USER_AGENT));
        sysLog.setParams(JsonUtil.toJsonString(request.getParameterMap()));
        sysLog.setCreateTime(new Date());
        sysLog.setDelFlag(0);
        return sysLog;
    }
}
